<template>
  <el-form>
    <el-form-item label="SPU名称">
      <el-input
        placeholder="请输入spu姓名"
        v-model="SpuParmas.spuName"
      ></el-input>
    </el-form-item>
    <el-form-item label="SPU品牌">
      <el-select placeholder="请选择品牌" v-model="SpuParmas.tmId">
        <el-option
          v-for="item in AllTardeMark"
          :key="item.id"
          :label="item.tmName"
          :value="item.id"
        ></el-option>
      </el-select>
    </el-form-item>
    <el-form-item label="SPU描述">
      <el-input
        placeholder="请输入描述"
        v-model="SpuParmas.description"
        type="textarea"
      ></el-input>
    </el-form-item>
    <el-form-item label="SPU图片">
      <el-upload
        v-model:file-list="AllSpuImage"
        action="/api/admin/product/fileUpload"
        list-type="picture-card"
        :on-preview="handlePictureCardPreview"
        :on-remove="handleRemove"
        :before-upload="handlereBeforeUpload"
      >
        <el-icon><Plus /></el-icon>
      </el-upload>

      <el-dialog v-model="dialogVisible">
        <img w-full :src="dialogImageUrl" alt="Preview Image" />
      </el-dialog>
    </el-form-item>
    <el-form-item label="SPU销售属性">
      <el-select
        :placeholder="`还有${noChooseAttr.length}个属性可选择`"
        v-model="idAndName"
      >
        <el-option
          v-for="item in noChooseAttr"
          :key="item.id"
          :label="item.name"
          :value="`${item.id}:${item.name}`"
        ></el-option>
      </el-select>
      <el-button
        type="primary"
        icon="Plus"
        style="margin-left: 10px"
        :disabled="idAndName ? false : true"
        @click="addSpuAttr"
        >添加属性值</el-button
      >
    </el-form-item>
    <el-form-item>
      <el-table border :data="SpuAttr">
        <el-table-column
          label="序号"
          type="index"
          align="center"
          width="80px"
        ></el-table-column>
        <el-table-column
          label="销售属性名字"
          width="120px"
          prop="saleAttrName"
        ></el-table-column>
        <el-table-column label="销售属性值">
          <template #="{ row }">
            <el-tag
              v-for="(item, index) in row.spuSaleAttrValueList"
              :key="item.id"
              class="mx-1"
              closable
              type="success"
              style="margin: 0px 8px"
              @close="row.spuSaleAttrValueList.splice(index, 1)"
            >
              {{ item.saleAttrValueName }}
            </el-tag>
            <el-input
              v-model="row.saleAttrValue"
              placeholder="请输入属性值"
              size="small"
              style="width: 100px; margin-right: 8px"
              v-if="row.flag"
              @blur="toLook(row)"
              ref="put"
            ></el-input>
            <el-button
              type="primary"
              icon="Plus"
              size="small"
              circle
              v-else
              @click="toEdit(row)"
            ></el-button>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120px">
          <template #="{ $index }">
            <el-button
              type="danger"
              icon="delete"
              size="small"
              @click="SpuAttr.splice($index, 1)"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-form-item>
    <el-form-item>
      <el-button
        type="primary"
        @click="Seave"
        :disabled="SpuAttr.length > 0 ? false : true"
        >保存</el-button
      >
      <el-button type="danger" @click="toSupLook">取消</el-button>
    </el-form-item>
  </el-form>
</template>

<script setup lang="ts">
import { ref, computed, nextTick } from "vue";
import { addOrUpdateSpu } from "@/api/produck/spu";
//引入接口
import {
  getAllTrademark,
  getSpuImageList,
  getSpuAttrList,
  getAllProduct,
} from "@/api/produck/spu";
import type {
  resAllTradeMarkList,
  resAllTradeMark,
  SpuAttrList,
  AttrList,
} from "@/api/produck/spu/type";
import { ElMessage } from "element-plus";
//收集所有的品牌
let AllTardeMark = ref<resAllTradeMark[]>([]);
//存储品牌图片
let AllSpuImage = ref<any[]>([]);
//存储对应的品牌属性
let SpuAttr = ref<SpuAttrList[]>([]);
//存储整个项目的品牌属性
let AllProduct = ref<AttrList[]>([]);
//展示图片的地址
let dialogImageUrl = ref<string>("");
//存储spu参数
let SpuParmas = ref<any>({
  category3Id: "", //哪一个三级分类id
  description: "", //品牌描述
  spuImageList: [], //图片列表
  spuName: "", //spu名称

  spuSaleAttrList: [],
  tmId: "",
});
//获取输入框
let put = ref();
//收集下拉菜单的属性
let idAndName = ref<string>("");
//控制对话框的显示与隐藏
let dialogVisible = ref<boolean>(false);
//自定义事件
const $emit = defineEmits(["changeScene"]);
//取消按钮的回调
const toSupLook = () => {
  //将场景值切换
  $emit("changeScene", { flag: 0 });
};
//计算没有选择的品牌属性
const noChooseAttr = computed(() => {
  return AllProduct.value.filter((item) => {
    return SpuAttr.value.every((item1) => {
      return item1.saleAttrName != item.name;
    });
  });
});
//获取品牌属性
const HasAllSpuList = async (spu: any) => {
  SpuParmas.value = spu;
  //获取所有品牌
  let result: resAllTradeMarkList = await getAllTrademark();
  //获取对应品牌的图片
  let result1: any = await getSpuImageList(spu.id);
  //获取某一个品牌下对应的品牌属性
  let result2: any = await getSpuAttrList(spu.id);
  //获取整个项目的品牌属性
  let result3: any = await getAllProduct();
  //将获取到的数据进行整合
  //存储全部数据
  AllTardeMark.value = result.data;
  //存储对应属性图片
  AllSpuImage.value = result1.data.map((item: any) => {
    return { name: item.imgName, url: item.imgUrl };
  });
  //存储对应属性
  SpuAttr.value = result2.data;
  //存储整个项目的品牌属性
  AllProduct.value = result3.data;
};
//点击图片放大的回调,注入一个参数flie,它拥有我们点击图片的全部信息
const handlePictureCardPreview = (flie: any) => {
  //让对话框显示
  dialogVisible.value = true;
  //将图片的地址赋值
  dialogImageUrl.value = flie.url;
};
//删除图片的回调
const handleRemove = () => {};
//添加spu属性的回调
/*
  baseSaleAttrId: number,
  saleAttrName: string,
  spuSaleAttrValueList: spuSaleAttrValueList,
*/
const addSpuAttr = () => {
  let arr = idAndName.value.split(":");
  //数组解构
  const [baseSaleAttrId, saleAttrName] = arr;
  //定义一个对象接收
  let obj: any = {
    baseSaleAttrId,
    saleAttrName,
    spuSaleAttrValueList: [],
  };
  //点击按钮就像数组里面添加一条对象
  SpuAttr.value.push(obj);
  //将idAndName清空
  idAndName.value = "";
};
//上传图片的回调
const handlereBeforeUpload = (file: any) => {
  //限制文件类型
  if (
    file.type == "image/png" ||
    file.type == "image/jpeg" ||
    file.type == "image/gif"
  ) {
    //限制图片大小
    if (file.size / 1024 / 1024 < 4) {
      return true;
    } else {
      ElMessage({
        type: "error",
        message: "上传图片大小不能超过4M",
      });
      return false;
    }
  } else {
    ElMessage({
      type: "error",
      message: "上传图片格式不正确",
    });
    return false;
  }
};
//添加spu属性值的方法
const toEdit = (row: any) => {
  //将上一次的数据清空
  row.saleAttrValue = "";
  //自动聚焦
  nextTick(() => {
    put.value.focus();
  });
  row.flag = true;
};
//input失去焦点的回调
const toLook = (row: any) => {
  if (row.saleAttrValue.trim() == "") {
    ElMessage({
      type: "error",
      message: "属性值不能为空",
    });
    row.flag = false;
    return;
  } else {
    let reapet = row.spuSaleAttrValueList.find((item: any) => {
      return item.saleAttrValueName == row.saleAttrValue;
    });
    if (reapet) {
      ElMessage({
        type: "error",
        message: "请勿输入重复值",
      });
      return;
    }
  }
  row.spuSaleAttrValueList.push({
    baseSaleAttrId: row.baseSaleAttrId,
    saleAttrValueName: row.saleAttrValue,
  });

  //切换模式
  row.flag = false;
};
//保存按钮的回调
const Seave = async () => {
  //整理数据
  SpuParmas.value.spuImageList = AllSpuImage.value.map((item: any) => {
    return {
      imgName: item.name,
      imgUrl: (item.response && item.response.data) || item.url,
    };
  });
  SpuParmas.value.spuSaleAttrList = SpuAttr.value;
  let result: any = await addOrUpdateSpu(SpuParmas.value);
  if (result.code == 200) {
    ElMessage({
      type: "success",
      message: SpuParmas.value.id ? "修改成功" : "添加成功",
    });
    $emit("changeScene", {
      flag: 0,
      parmas: SpuParmas.value.id ? "update" : "add",
    });
  } else {
    ElMessage({
      type: "error",
      message: result.message,
    });
  }
};
//添加spu属性方法(父组件调用)
const addSonAttr = async (c3Id: number | string) => {
  //将上一次的数据清空
  Object.assign(SpuParmas.value, {
    category3Id: "", //哪一个三级分类id
    description: "", //品牌描述
    spuImageList: [], //图片列表
    spuName: "", //spu名称

    spuSaleAttrList: [],
    tmId: "",
  });
  //清空图片和添加的属性
  SpuAttr.value = [];
  AllSpuImage.value = [];
  //将父组件传递的数据接收
  SpuParmas.value.category3Id = c3Id;
  //发送两个请求
  //获取所有品牌
  let result: resAllTradeMarkList = await getAllTrademark();
  //获取整个项目的品牌属性
  let result3: any = await getAllProduct();
  //存储全部数据
  AllTardeMark.value = result.data;
  //存储整个项目的品牌属性
  AllProduct.value = result3.data;
};
//暴露方法
defineExpose({ HasAllSpuList, addSonAttr });
</script>
